package com.example.androidaudiovideodemo

import android.opengl.GLES20
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer

/**
 *
 * author: renbing
 *
 * date: 2022/1/14
 *
 * des:
 */
class Triangle {

    private var vertexBuffer: FloatBuffer? = null

    //顶点着色器
    private val vertexShaderCode =
        "attribute vec4 vPosition;"+
             "void main() {"+
             "  gl_Position = vPosition;"+
             "}"

    //片元着色器
    private val fragmentShaderCode =
        "precision mediump float;"+
                "uniform vec4 vColor;"+
                "void main() {"+
                "   gl_FragColor = vColor;"+
                "}"
    //每个点的坐标值
    private val COORDS_PER_VERTEX = 3
    //坐标  原点在GLSurfaceView中心，坐标值类型为float 1到各个边界  是百分比  所以这也导致横竖屏切换图形会变形
    private val triangleCoords = floatArrayOf(
        0f,1f,0f,
        -1f,0f,0f,
        1f,-0f,0f)

    private val color = floatArrayOf(0f, 0f, 1f, 1.0f)

    private var mProgram = 0

    private var mPositionHandle = 0
    private var mColorHandle = 0

    private val vertexCount = triangleCoords.size/COORDS_PER_VERTEX
    private val vertexStride = COORDS_PER_VERTEX*4

    init {
        val byteBuffer = ByteBuffer.allocateDirect(triangleCoords.size*4)
        byteBuffer.order(ByteOrder.nativeOrder())

        vertexBuffer = byteBuffer.asFloatBuffer()
        vertexBuffer?.run {
            put(triangleCoords)
            position(0)
        }
        //装载获取顶点着色器
        val vertexShader = MyGLRenderer.loadShader(GLES20.GL_VERTEX_SHADER,vertexShaderCode)
        //装载获取片元着色器
        val fragmentShader = MyGLRenderer.loadShader(GLES20.GL_FRAGMENT_SHADER,fragmentShaderCode)
        //获取一个空的program
        mProgram = GLES20.glCreateProgram()
        //program绑定顶点着色器
        GLES20.glAttachShader(mProgram,vertexShader)
        //program绑定片元着色器
        GLES20.glAttachShader(mProgram,fragmentShader)
        //创建可执行的OpenGL ES程序
        GLES20.glLinkProgram(mProgram)
    }

    fun draw(){
        //将程序加入到OpenGL ES环境中
        GLES20.glUseProgram(mProgram)
        //获取顶点着色器的vPosition成员位置
        mPositionHandle = GLES20.glGetAttribLocation(mProgram,"vPosition")
        //激活
        GLES20.glEnableVertexAttribArray(mPositionHandle)
        //准备三角形的坐标数据
        GLES20.glVertexAttribPointer(mPositionHandle,COORDS_PER_VERTEX,GLES20.GL_FLOAT,false,vertexStride,vertexBuffer)

        //获取片元着色器的vColor成员位置
        mColorHandle = GLES20.glGetUniformLocation(mProgram,"vColor")
        GLES20.glUniform4fv(mColorHandle,1,color,0)
        GLES20.glDrawArrays(GLES20.GL_TRIANGLES,0,vertexCount)
        GLES20.glDisableVertexAttribArray(mPositionHandle)

    }
}